
import 'dart:async';

import 'package:get/get.dart';
import 'package:work_tools/dio/api.dart';
import 'package:work_tools/dio/http.dart';
import 'package:work_tools/model/token_entity.dart';
import 'login_sheet_state.dart';

class LoginSheetLogic extends GetxController {
  final state = LoginSheetState();


  smsCode() async {
    try {
      if (state.loading) return;
      state.loading = true;
      await api.smsCodeByEncrypt(state.mobile());
      state.isSmsCode(true);
      state.countdownTime(state.totalTime);
      state.loading = false;
      Timer.periodic(const Duration(seconds: 1) , (timer){
        state.countdownTime(state.countdownTime()-1);
        if(state.countdownTime()<=0){
          timer.cancel();
          state.isSmsCode(false);
        }
      });
    } catch (e) {
      state.loading = false;

    }
  }

  login() async {
    if (state.loading) return;
    state.loading = true;
    TokenEntity? data;
    try {
      data = await api.loginSms(state.mobile(), state.code());
    } catch (e) {
      state.loading = false;
      return;
    }
    try {
      final aId = data?.aId ?? "";
      final rId = data?.rId ?? "";
      if (aId.isEmpty || rId.isEmpty) {
        state.loading = false;
        return;
      }
      Http.setToken(aId, rId);
      Get.back();
      state.loading = false;
    } catch (e) {
      Get.back();
      state.loading = false;
    }
  }
}